﻿using System;
using System.Collections.Generic;
using System.Linq;
using oModbus.Utility;

namespace oModbus.Message
{
    public class ReadInputRegisterRequest : AbstractModbusMessage
    {
        public ReadInputRegisterRequest(byte slaveAddress, ushort startAddress, ushort number) : base(slaveAddress, FunctionCode.ReadInputRegister)
        {
            StartAddress = startAddress;
            Number = number;
        }

        public ReadInputRegisterRequest(byte[] messageBytes) : base(messageBytes)
        {
        }
        /// <summary>
        /// 开始地址
        /// </summary>
        public ushort StartAddress { get; set; }
        /// <summary>
        /// 读取数量
        /// </summary>
        public ushort Number { get; set; }



        protected override void Packing()
        {
            base.Packing();
            MessageData.AddRange(StartAddress.GetBytes());//开始地址
            MessageData.AddRange(Number.GetBytes());//长度  
            Crc = MessageData.ToArray().CalculateCrc();
            
        }

        public override bool Analysis(byte[] messageBytes)
        {
            if (messageBytes.Length >= 8)
            {
                MessageData = messageBytes.ToList();
                SlaveAddress = messageBytes[0];
                FunctionCode = (FunctionCode)Convert.ToInt32(messageBytes[1]);
                StartAddress = ConvertExtend.GetUint16(messageBytes[2], messageBytes[3]);
                Number = ConvertExtend.GetUint16(messageBytes[4], messageBytes[5]);

                Crc = new List<byte>() {
                    messageBytes[messageBytes.Length - 2],
                    messageBytes[messageBytes.Length - 1]
                }.ToArray();
                return true;
            }
            return false;
        }
    }

}
